<template>
  <el-row class="web-online-base-config">
    <el-form ref="newForm" :model="newForm" label-position="left" labelWidth="120px">
      <el-form-item label="接入名称">
        <el-input v-model.trim="newForm.name" size="mini" style="width: 440px"></el-input>
      </el-form-item>
      <el-form-item label="系统欢迎语：">
        <div>
          <div class="remark">
            <span>点击“+”即可将占位符填充到您输入内容的后方。</span>
            <el-tooltip class="item" effect="dark" popper-class="reportTip" placement="bottom" style="opacity: 1;">
              <div slot="content">
                占位符是指系统自动获取的客户和座席相关信息，可用于配制组合欢迎语内容，如：亲爱的{nickName}您好，其中{nickName}为获取到的访客名称。<br/>
                注意：获取的信息为您接入网站代码时定义的相关信息，如需使用占位符，请先在接入网站时接入相关代码。
              </div>
              <span class="tip"><i class="iconfont icon-tixingweizhi"></i></span>
            </el-tooltip>
          </div>
          <div class="placeholder_box">
            <span v-for="place in placeholderArr" @click.stop="addPlaceholder(place.data)" :title="place.content">
              {{place.content}}<i class="iconfont icon-zhankai"></i>
            </span>
          </div>
          <el-input
            style="width: 440px"
            type="textarea"
            :rows="2"
            placeholder="您好欢迎光临"
            v-model="newForm.welcome">
          </el-input>
        </div>
      </el-form-item>
      <el-form-item label="技能组：" class="margin-top">
        <!-- <div class="skill_group"> -->
          <!-- <el-select v-model="skillInitVal" placeholder="请选择">
            <el-option
              label="默认"
              value="default">
            </el-option>
          </el-select> -->
          <!-- <el-button @click.stop="addSkill" size="small" class="add-btn">添加技能组</el-button> -->
        <!-- </div> -->
        <!-- <div class="item_group"> -->
          <div class="item_li" v-for="(ToPeerItem, index) in newForm.ToPeer">
            <el-select
              class="float-l with-160"
              size="mini"
              filterable
              v-model.trim="ToPeerItem.id"
              :placeholder="$t('webchat.placeSkillsGrouop')"
              @change="choseSkill(ToPeerItem, index, peerOptions)"
              @visible-change="showSkillDialog"
              :disabled="ToPeerItem.status === 'disable'">
              <el-option
                v-for="item in peerOptions"
                :key="item.id"
                :label="item.DisplayName"
                :value="item.Exten">
              </el-option>
            </el-select>
              <el-input v-model.trim="ToPeerItem.name" class="tooper_name_class float-l" :disabled="ToPeerItem.status === 'disable'" :placeholder="$t('webchat.typeName')"></el-input>
              <el-checkbox class="float-l" :disabled="true" v-model="ToPeerItem.checked" @change="topeerEnable(ToPeerItem)">是否启用</el-checkbox>
              <!-- <i class="el-icon-minus del float-l" @click.stop="deletePeerItem(index)"></i> -->
          </div>
        <!-- </div> -->
      </el-form-item>
      <el-form-item label="商户简称">
        <el-input v-model.trim="newForm.companyName" size="mini" style="width: 440px"></el-input>
      </el-form-item>
      <el-form-item label="商户头像：" style="margin-top: 10px">
        <el-progress :text-inside="true" :stroke-width="18" :percentage="systemMsgLogoUi.percent" :status="systemMsgLogoUi.type" v-if="systemMsgLogoUi.show"></el-progress>
        <div class="wrap_logo">
          <img v-show="newForm.systemMsgLogo" :src="newForm.systemMsgLogo" alt="" class="logo fl">
          <span class="upload-btn" id="uploadSystemLogo">点击上传图片</span>
          <span class="del_upload_file" v-show="newForm.systemMsgLogo" @click="deleteUploadFile">删除</span>
          <el-tooltip class="item" effect="dark" popper-class="reportTip" placement="bottom" style="opacity: 1;">
            <div slot="content">
              上传的头像应用于系统消息头像、座席头像、访客端商户信息展示
            </div>
            <span class="tip" style="margin-left: 10px"><i class="iconfont icon-tixingweizhi"></i></span>
          </el-tooltip>
        </div>
        <div class="desc">支持jpg/jpeg/png/gif格式图片，文件需小于2MB</div>
      </el-form-item>
      <el-form-item label="显示座席昵称：">
        <el-switch
          v-model="newForm.showAgentName"
          active-color="#459ae9"
          inactive-color="#ccc">
        </el-switch>
      </el-form-item>
      <el-form-item label="启用满意度：" style="margin-top: -5px">
        <el-switch
          v-model="newForm.webchat_csr"
          active-color="#459ae9"
          inactive-color="#ccc">
        </el-switch>
      </el-form-item>
    </el-form>
  </el-row>
</template>
<script>
  import {uploadTo7moorlogoImgDomain} from '@/utils/qiniuUtils'
  import {getCurrentDate, deepClone} from '@/utils/m7Utils'
  import * as uuid from 'uuid'
  export default {
    name: 'baseConfig',
    data () {
      return {
        newForm: {
          companyName: '',
          name: '',
          systemMsgLogo: '',
          welcome: '', // 欢迎语
          showAgentName: true,
          webchat_csr: true,
          ToPeer: []
        },
        m7uploaders: [],
        systemMsgLogoUi: {       //  系统消息头像上传进度条
          show: false,
          percent: 0,
          type: 'success',
          fileName: '',
          disabled: false
        },
        skillInitVal: 'default',
        peerOptions: [],
        placeholderArr: [       //  客服欢迎词占位符
          {
            content: this.$t('configLazyLoad.channel.nickName'),
            data: 'nickName'
          }
        ]
      }
    },
    props: {
    },
    watch: {
    },
    components: {
    },
    computed: {
    },
    methods: {
      open (val, isAdd) {
        if (isAdd) {
          this.newForm = {
            companyName: '',
            name: '',
            systemMsgLogo: '',
            welcome: '', // 欢迎语
            showAgentName: true,
            webchat_csr: true,
            ToPeer: []
          }
        } else {
          for (let key in this.newForm) {
            this.newForm[key] = deepClone(val[key])
          }
        }
      },
      // 上传图片初始化的事件
      initUploadImageFile () {
        let account = this.$store.state.session.user.account
        let self = this
        let fileAdded = function (up, files) {}
        let beforeUploadSysLogo = function (up, file) {
          self.systemMsgLogoUi.show = true
          self.systemMsgLogoUi.percent = 0
        }
        let upProgressSysLogo = function (up, file) {
          self.systemMsgLogoUi.percent = file.percent
        }
        let upCompleteSysLogo = function (up, file) {
          self.systemMsgLogoUi.show = false
        }
        let systemLogouploaded = function (up, file, info) {
          let domain = up.getOption('domain')
          let res = JSON.parse(info||'{}')
          let sourceLink = domain + (self.$store.state.isUseQiniu ? res.key : file.fileKey) // 获取上传成功后的文件的Url
          if (!sourceLink) {
            return
          }
          self.$set(self.newForm, 'systemMsgLogo', sourceLink)
          self.$message.success('图片上传成功')
        }
        let error = function (up, err, errTip) {
          if (errTip) {
            self.$message.error(errTip)
          }
        }
        let key = function (up, file) {
          let date = getCurrentDate()
          let today = new Date()
          let time = today.getTime()
          let key = account + '/km/' + date + '/' + time + '/' + uuid.v1() + file.name
          return key
        }
        let filters = {
          mime_types: [
            {title: 'Image files', extensions: 'jpg,gif,png,jpeg'}
          ]
        }
        this.m7uploaders.push(
          uploadTo7moorlogoImgDomain(this.$store.state.session.user._id, 'uploadSystemLogo', filters, fileAdded, beforeUploadSysLogo, upProgressSysLogo, upCompleteSysLogo, systemLogouploaded, error, key)
        )
      },
      addSkill () {
        this.newForm.ToPeer.push({id: '', name: '', checked: true, status: 'enable'})
      },
      showSkillDialog (show) {
        if (show) {
          this.$store.dispatch('getCache', { type: 'mailQueues' }).then(req => {
            let mailQueues = this.$getCache('mailQueues')
            this.peerOptions = mailQueues || []
          })
        }
      },
      //      是否启用技能组
      topeerEnable (data) {
        if (data.checked) {
          this.$set(data, 'status', 'enable')
        } else {
          this.$set(data, 'status', 'disable')
        }
      },
      choseSkill (data, indexData, array) {
        var typeName = array.filter(function (item, index) {
          return item.Exten === data.id
        })
        var flag = true
        this.newForm.ToPeer.forEach((obj, index) => {
          if (obj.id === typeName[0].Exten && index !== indexData) {
            flag = false
          }
        })
        if (typeName[0].DisplayName && flag) {
          data.name = typeName[0].DisplayName
        } else {
          data.id = ''
          data.name = ''
          this.$message.error('技能组不可重复')
        }
      },
      deletePeerItem (index) { // 删除技能组
        this.newForm.ToPeer.splice(index, 1)
      },
      changeForm () {
        this.newForm = deepClone(this.form)
      },
      deleteUploadFile () {
        this.newForm.systemMsgLogo = ''
      },
      addPlaceholder (data) {
        this.newForm.welcome += '{' + data + '}'
      }
    },
    mounted () {
      this.$nextTick(() => {
        this.initUploadImageFile()
      })
    },
    beforeDestroy () {
      this.m7uploaders.forEach(uploader => {
        uploader &&
        uploader.destroy &&
        uploader.destroy()
      })
    },
    beforeMount () {
      this.$store.dispatch('getCache', { type: 'mailQueues' }).then(req => {
        let mailQueues = this.$getCache('mailQueues')
        this.peerOptions = mailQueues || []
      })
    }
  }
</script>
<style lang="stylus">
.web-online-base-config
  .el-form-item__content
    font-size 12px
</style>
<style lang="stylus" scoped>
@import "../../../../../assets/common.styl"
.web-online-base-config
  .remark
    color #3b5998
  .tip
    cursor pointer
    display inline-block
    height 16px
    width 16px
    border 1px solid $c-main
    text-align center
    line-height 16px
    border-radius 50%
    margin-left 2px
    .iconfont
      font-size 10px
      color $c-main
  .margin-top
    margin-top 15px
  .float-l
    float left
  .with-160
    width 160px
  .placeholder_box
    span
      border 1px solid $c-main
      color $c-main
      border-radius 3px
      padding 5px 7px
      margin 10px 0px
      cursor pointer
  .skill_group
    .add-btn
       margin-left 10px
  .item_li
    // clear both
    .tooper_name_class
      width 160px
      margin 0px 10px
    .el-icon-minus
      margin-left: 10px;
      color: #fff;
      background-color: $c-pink;
      border-radius: 50%;
      margin-top: 10px;
      padding: 3px 3px;
      cursor: pointer;
  .desc
    color #3b5998
    clear both
    line-height 18px
  .wrap_logo
    .logo
      max-width: 36px;
      max-height: 36px;
      margin-right: 20px;
    .upload-btn
      background: rgba(255,255,255,1);
      border-radius: 3px;
      border: 1px solid rgba(220,223,230,1);
      color: #666666;
      padding: 5px 8px;
      cursor pointer
    .del_upload_file
      color $c-pink
      margin-left 10px
.iconfont
  font-size 12px
</style>
